$(function () {
    $(document).ready(function () {
        // 初始化待归档事件信息
        initUnAchievedEventReg();
        // 初始化归档信息
        initAchievedEventReg();
        // 待接收
        initWaitingEventReg();
        //上报历史
        initHistory();
        GetYourLocation();
    });
});
var map;

function GetYourLocation() {
    $("#locationDes").html("正在获取位置......");

    var geolocation = new BMap.Geolocation();
    geolocation.getCurrentPosition(function (r) {
        if (this.getStatus() == BMAP_STATUS_SUCCESS) {
            var pt = new BMap.Point(r.point.lng, r.point.lat);
            $("#lng").val(r.point.lng);
            $("#lat").val(r.point.lat);
            var geoc = new BMap.Geocoder();
            geoc.getLocation(pt, function (rs) {// 解析格式：城市，区县，街道
                var addComp = rs.addressComponents;
                var s = '<img width="5%" src="/wcsi/img/yourlocation.png"/>';
                $("#locationDes").html(s + addComp.city + "," + addComp.district + "," + addComp.street);
                $("#archiveAddr").val(addComp.city + "," + addComp.district + "," + addComp.street);
            });
        } else {
            $("#locationDes").html('定位失败');
        }
    }, {
        enableHighAccuracy: true
    })// 指示浏览器获取高精度的位置，默认false
};
// =====================退回按钮===============
$(document).on("click", "#tuihuiBtn", function () {
    var eventId = $("#waitRegister_eventId").val();
    // 退回页面
    if (confirm('确定退回该事件?')) {
        window.location.href = rootPath + '/ui/archive/backRegisterUI/' + eventId + "?device=mobile&identify=";
    }

});

// ======================接收按钮===================
$(document).on("click", "#jieshouBtn", function () {

    var eventId = $("#waitRegister_eventId").val();

    $.ajax({
        url: rootPath + "/ui/archive/receptRegister/" + eventId,
        dataType: 'json',
        type: 'get',
        success: function (result) {
            if (result.code == 1) {
                alert("接收成功!");
                window.location.href = rootPath
                    + '/ui/archive?device=mobile&identify=';
                $("#jieshouBtn").prop("disabled", true);
                $("#popupView").popup("open");
            }
        }
    });

});

// =====================主页========================
$(document).on("click", "#goHome", function () {
    $("#goHome").attr("href", $("#goHome").attr("href") + "&&identify=");
    $("#goHome2").attr("href", $("#goHome2").attr("href") + "&&identify=");
    $("#goHome3").attr("href", $("#goHome3").attr("href") + "&&identify=");
});

// ==================图片============================
$(document).on('click', '#fileclick', function () {
    return $("#file_upload").click();
});
$(document).on("change", "#file_upload", function () {
    var $file = $(this);
    var fileObj = $file[0];
    var windowURL = window.URL || window.webkitURL;
    var dataURL;
    var $img = $("#avatart");

//	if (fileObj && fileObj.files && fileObj.files[0]) {
//		dataURL = windowURL.createObjectURL(fileObj.files[0]);
//		$img.attr('src', dataURL);
//	} else {
//		dataURL = $file.val();
//		var imgObj = document.getElementById("preview");
//		// 两个坑:
//		// 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
//		// 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
//		imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
//		imgObj.filters
//				.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
//
//	}


    if (fileObj && fileObj.files && fileObj.files[0]) {
        dataURL = windowURL.createObjectURL(fileObj.files[0]);
        var img = new Image();
        img.src = dataURL;


        img.onload = function () {
            getPhotoOrientation(img, $img);
            var file = document.getElementById($file.attr("id"));
            file.value = '';
        }
    } else {
        dataURL = $file.val();
        var imgObj = document.getElementById("preview");
        // 两个坑:
        // 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
        // 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
        imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
        imgObj.filters
            .item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;

    }
});

function getPhotoOrientation(img, $img) {
    var Orientation;
    EXIF.getData(img, function () {
        $("#popupView").popup("open");
        Orientation = EXIF.getTag(this, 'Orientation');

        var _imgWidth_act = img.naturalWidth;     //图片宽度
        var _imgHeight_act = img.naturalHeight;   //图片高度

        var _imgWidth = img.naturalWidth;     //图片宽度
        var _imgHeight = img.naturalHeight;   //图片高度

        if (_imgWidth_act > 400) {
            _imgWidth = 400;
            _imgHeight = (400 * _imgHeight_act) / _imgWidth_act;
        }
        var canvas = document.createElement('canvas');
        canvas.width = _imgWidth;
        canvas.height = _imgHeight;
        var ctx = canvas.getContext('2d');

        if (Orientation && Orientation != 1) {
            switch (Orientation) {
                case 6:     // 旋转90度
                    canvas.width = _imgHeight;
                    canvas.height = _imgWidth;
                    ctx.rotate(Math.PI / 2);
                    // (0,-imgHeight) 从旋转原理图那里获得的起始点
                    ctx.drawImage(this, 0, -_imgHeight, _imgWidth, _imgHeight);
                    break;
                case 3:     // 旋转180度
                    ctx.rotate(Math.PI);
                    ctx.drawImage(this, -_imgWidth, -_imgHeight, _imgWidth, _imgHeight);
                    break;
                case 8:     // 旋转-90度
                    canvas.width = _imgHeight;
                    canvas.height = _imgWidth;
                    ctx.rotate(3 * Math.PI / 2);
                    ctx.drawImage(this, -_imgWidth, 0, _imgWidth, _imgHeight);
                    break;
            }
        } else {
            ctx.drawImage(img, 0, 0, _imgWidth, _imgHeight);
        }

        /*ctx.rotate(Math.PI / 2);
        ctx.drawImage(img,0, 0, _imgWidth,_imgHeight);*/

        $img.attr('src', canvas.toDataURL('dimg/png'));
        $("#popupView").popup("close");
    });
}


// ===========================归档=============================
$(document).on("click", "#archiveBtn", function () {
    var lng = 0;
    if ($("#lng").val() != undefined && $("#lng").val() != "") {
        lng = $("#lng").val();
    }
    var lat = 0;
    if ($("#lat").val() != undefined && $("#lat").val() != "") {
        lat = $("#lat").val();
    }
    var archiveAddr = '';
    if ($("#archiveAddr").val() != undefined && $("#archiveAddr").val() != "") {

        archiveAddr = $("#archiveAddr").val();
    }


    var eventId = $("#unArchievedEventReg_eventId").val().trim();
    var content = $("#content").val().trim();
    var memo = $("#memo").val().trim();
    var eventImg = $("#avatart").attr("src");

    var archiveInfo = {
        "photourl": eventImg,
        "longtitude": lng,
        "latitude": lat,
        "archiveAddr": archiveAddr,
        "content": content,
        "memo": memo

    };
    var data = {
        "archiveInfo": JSON.stringify(archiveInfo)
    }

    if (confirm("确认归档该条信息?")) {

        // 前台校验是否已经被归档
        $.ajax({
            url: rootPath + "/ui/archive/checkState/" + eventId,
            dataType: 'json',
            type: 'GET',
            success: function (result) {
                if (result.code == 1) {

                    if (_phoneType == "Android") {
                        window.jump.proShow();
                    } else if (_phoneType == "Ios") {
                        window.webkit.messageHandlers.submitWaiting.postMessage({body: 'open'});
                    } else {
                        $("#popupView").popup("open");
                    }

                    //解决IOS上传bug,重新使用上传方法
                    $.ajax({
                        url: window.rootPath + "/ui/archive/archiveEventWithoutInputFile/" + eventId,
                        dataType: 'json',
                        type: 'post',
                        data: data,
                        success: function (result) {
                            if (_phoneType == "Android") {
                                window.jump.proDismiss();
                            } else if (_phoneType == "Ios") {
                                window.webkit.messageHandlers.submitWaiting.postMessage({body: 'close'});
                            } else {
                                $("#popupView").popup("close");
                            }
                            alert("归档成功");
                            $("#archiveBtn").prop("disabled", true);
                            window.location.href = rootPath + "/ui/archive?device=mobile&&identify=";
                        }
                    });
                    return;

                    $.ajaxFileUpload({
                        url: window.rootPath + "/ui/archive/archiveEvent/" + eventId,
                        secureuri: false,// 是否需要安全协议
                        fileElementId: 'file_upload',// 文件上传的Id属性
                        dataType: 'text',
                        data: data,
                        success: function (result, status) {
                            if (_phoneType == "Android") {
                                window.jump.proDismiss();
                            } else if (_phoneType == "Ios") {
                                window.webkit.messageHandlers.submitWaiting.postMessage({body: 'close'});
                            } else {
                                $("#popupView").popup("close");
                            }
                            alert("归档成功");
                            $("#archiveBtn").prop("disabled", true);
                            window.location.href = rootPath + "/ui/archive?device=mobile&&identify=";
                        }
                    });


                } else {
                    alert("该记录已经被归档,无法再次归档");
                }
            }
        });

    }
});
// ===================================================

// ===============================初始化待接收======================
function initWaitingEventReg() {
    $.ajax({
        url: rootPath
            + "/ui/archive/initWaitingEventReg?device=mobile&identify=",
        dataType: 'json',
        type: 'get',
        success: function (result) {
            if (result.code == 1) {
                var regs = result.data.waitingEventReg;
                buildPage2("#waitRegister", regs);
            }
        }
    });
};

//===============================上报历史===============================
function initHistory() {

    $.ajax({
        url: rootPath + "/ui/archive/initHistory?device=mobile&identify=",
        dataType: 'json',
        type: 'get',
        success: function (result) {
            if (result.code == 1) {
                var regs = result.data.histories;
                initHistoryPage("#history", regs);
            }
        }
    });
};

function initHistoryPage(str, regs) {
    $(str).empty();
    if (regs.length == 0) {
        var contentval = '<li><h2 style="color:blue">暂无事件信息</h2></li>';
        $(str).append(contentval);
        $(str).listview('refresh');
    }
    for (var i = 0; i < regs.length; i++) {

        var purl = regs[i].reportImgAdress;

        if (purl == undefined || purl == "") {
            purl = "img/nopicture.png";
        }
        purl = window.rootPath + "/" + purl;
        var eventTaskMemo = regs[i].reportMemo;
        if (eventTaskMemo == '' || undefined == eventTaskMemo) {
            eventTaskMemo = "该事件无备注";
        }
        var s = '<img width="4%" src="/wcsi/img/yourlocation.png"/>' + regs[i].reportAdress;
        var contenthtml = '<li><a style="background-color:#FFFFFF;" href="#" data-transition="slide" defindStr="' + str + '" class="hrefClickR" defineId="' + regs[i].id + '" id="' + regs[i].id + '">'
            + '<div class="listViewImg">'
            + '<img src="' + purl + '"/>'
            + '</div>'
            + '<div class="listViewContent">'
            + '<p class="listViewTitle margin-Title"><font color="red">' + moment(regs[i].reportAccTime).format('YYYY-MM-DD HH:mm') + '</font></p>'
            + '<p class="listViewMemo margin-Title">&nbsp;' + regs[i].reportEventType.eventName + '<br/>&nbsp;' + eventTaskMemo + '<br/>' + s + '</p>'
            //		+ '<p class="listViewMemo">&nbsp;'+eventTaskMemo+'<br/>'+s+'</p>'
            + '</div>';
        contenthtml += '</a></li>';
        $(str).append(contenthtml);
    }
    $(str).listview('refresh');
    for (var i = 0; i < regs.length; i++) {
        $("#" + regs[i].id).removeClass("ui-btn-icon-right");
    }
    /*if (regs.length == 0) {
        var contentval = '<li><h2 style="color:blue">暂无事件信息</h2></li>';
        $(str).append(contentval);
        $(str).listview('refresh');
    }
    for (var i = 0; i < regs.length; i++) {

        var purl = regs[i].reportImgAdress;

        if (purl == undefined || purl == "") {
            purl = "img/nopicture.png";
        }
        purl = window.rootPath + "/" + purl;
        var contenthtml='<li><a style="background-color:#FFFFFF;" href="#" data-transition="slide" defindStr="'+str+'" class="hrefClick" defineId="'+regs[i].id+'" id="'+regs[i].id+'">'
        + '<img src="'+purl+'" style="margin-top:1em;margin-left:1em;width:70px;height:70px"/>'
        + '<h2 style="">'+moment(regs[i].reportAccTime).format('YYYY-MM-DD HH:mm')+'&nbsp;&nbsp;&nbsp;&nbsp;'+ regs[i].reportEventType.eventName+'</h2>'
        + '<p style="color:#999999;">&nbsp;'+regs[i].reportAdress+'</p>'
        + '<p style="color:#999999;">&nbsp;'+regs[i].reportUser.name+'&nbsp;&nbsp;&nbsp;'+regs[i].reportUser.contactType+'</p>';
        contenthtml+='</a></li>';
        $(str).append(contenthtml);
    }
    $(str).listview('refresh');
    for(var i=0;i<regs.length;i++){
        $("#"+regs[i].id).removeClass("ui-btn-icon-right");
    }*/
};

// =============================初始化归档信息=============================
function initAchievedEventReg() {
    $.ajax({
        url: rootPath
            + "/ui/archive/initArchievedEventReg?device=mobile&identify=",
        dataType: 'json',
        type: 'get',
        success: function (result) {
            if (result.code == 1) {
                var regs = result.data.archievedEventReg;
                unArchievedEventReg("#archievedEventReg", regs);
            }
        }
    });
};

// ====================================构建页面================================
function buildPage(str, regs) {
    $(str).empty();
    if (regs.length == 0) {
        var contentval = '<li><h2 style="color:blue">暂无事件信息</h2></li>';
        $(str).append(contentval);
        $(str).listview('refresh');
    }
    for (var i = 0; i < regs.length; i++) {

        var purl = regs[i].registerEventImgAdress;

        if (purl == undefined || purl == "") {
            purl = "img/nopicture.png";
        }
        purl = window.rootPath + "/" + purl;
        var eventTaskMemo = regs[i].registerEventMemo;
        if (eventTaskMemo == '' || undefined == eventTaskMemo) {
            eventTaskMemo = "该事件无备注";
        }
        var s = '<img width="4%" src="/wcsi/img/yourlocation.png"/>' + regs[i].registerEventAdress;
        var contenthtml = '<li><a style="background-color:#FFFFFF;" href="#" data-transition="slide" defindStr="' + str + '" class="hrefClick" defineId="' + regs[i].id + '" id="' + regs[i].id + '">'
            + '<div class="listViewImg">'
            + '<img src="' + purl + '"/>'
            + '</div>'
            + '<div class="listViewContent">'
            + '<p class="listViewTitle margin-Title"><font color="red">' + moment(regs[i].eventTaskTime).format('YYYY-MM-DD HH:mm') + '</font>&nbsp;&nbsp' + regs[i].registerEventName + '</p>'
            + '<p class="listViewMemo margin-Title">&nbsp;' + regs[i].registerEventName + '&nbsp;&nbsp;&nbsp;&nbsp;' + regs[i].registerEventSeriousLevel.title
            + '<br/>&nbsp;' + eventTaskMemo + '<br/>' + s + '</p>'
            + '</div>';
        contenthtml += '</a></li>';
        $(str).append(contenthtml);
    }
    $(str).listview('refresh');
    for (var i = 0; i < regs.length; i++) {
        $("#" + regs[i].id).removeClass("ui-btn-icon-right");
    }
};

function buildPage2(str, regs) {
    $(str).empty();
    if (regs.length == 0) {
        var contentval = '<li><h2 style="color:blue">暂无事件信息</h2></li>';
        $(str).append(contentval);
        $(str).listview('refresh');
    }
    for (var i = 0; i < regs.length; i++) {

        var purl = regs[i].registerEventImgAdress;

        if (purl == undefined || purl == "") {
            purl = "img/nopicture.png";
        }
        purl = window.rootPath + "/" + purl;
        var eventTaskMemo = regs[i].registerEventMemo;
        if (eventTaskMemo == '' || undefined == eventTaskMemo) {
            eventTaskMemo = "该事件无备注";
        }
        var s = '<img width="4%" src="/wcsi/img/yourlocation.png"/>' + regs[i].registerEventAdress;
        var contenthtml = '<li><a style="background-color:#FFFFFF;" href="#" data-transition="slide" defindStr="' + str + '" class="hrefClick" defineId="' + regs[i].id + '" id="' + regs[i].id + '">'
            + '<div class="listViewImg">'
            + '<img src="' + purl + '"/>'
            + '</div>'
            + '<div class="listViewContent">'
            + '<p class="listViewTitle margin-Title"><font color="red">' + moment(regs[i].registerEventAccTime).format('YYYY-MM-DD HH:mm') + '</font>&nbsp;&nbsp' + regs[i].registerEventName + '</p>'
            + '<p class="listViewMemo margin-Title">&nbsp;' + regs[i].registerEventName + '&nbsp;&nbsp;&nbsp;&nbsp;' + regs[i].registerEventSeriousLevel.title
            + '<br/>&nbsp;' + eventTaskMemo + '<br/>' + s + '</p>'
            + '</div>';
        contenthtml += '</a></li>';
        $(str).append(contenthtml);
    }
    $(str).listview('refresh');
    for (var i = 0; i < regs.length; i++) {
        $("#" + regs[i].id).removeClass("ui-btn-icon-right");
    }
};

// 处理中
function unArchievedEventReg(str, regs) {
    $(str).empty();
    if (regs.length == 0) {
        var contentval = '<li><h2 style="color:blue">暂无事件信息</h2></li>';
        $(str).append(contentval);
        $(str).listview('refresh');
    }
    for (var i = 0; i < regs.length; i++) {

        var purl = regs[i].registerEventImgAdress;

        if (purl == undefined || purl == "") {
            purl = "img/nopicture.png";
        }
        purl = window.rootPath + "/" + purl;
        var eventTaskMemo = regs[i].registerEventMemo;
        if (eventTaskMemo == '' || undefined == eventTaskMemo) {
            eventTaskMemo = "该事件无备注";
        }
        var s = '<img width="4%" src="/wcsi/img/yourlocation.png"/>' + regs[i].registerEventAdress;
        var contenthtml = '<li><a style="background-color:#FFFFFF;" href="#" data-transition="slide" defindStr="' + str + '" class="hrefClick" defineId="' + regs[i].id + '" id="' + regs[i].id + '">'
            + '<div class="listViewImg">'
            + '<img src="' + purl + '"/>'
            + '</div>'
            + '<div class="listViewContent">'
            + '<p class="listViewTitle margin-Title"><font color="red">' + moment(regs[i].registerEventAccTime).format('YYYY-MM-DD HH:mm') + '</font>&nbsp;&nbsp;' + regs[i].registerEventName + '</p>'
            + '<p class="listViewMemo margin-Title">&nbsp;' + regs[i].eventName + '&nbsp;&nbsp;&nbsp;&nbsp;' + regs[i].registerEventSeriousLevelTitle
            + '<br/>&nbsp;' + eventTaskMemo + '<br/>' + s + '</p>'
            + '</div>';
        contenthtml += '</a></li>';
        $(str).append(contenthtml);
    }
    $(str).listview('refresh');
    for (var i = 0; i < regs.length; i++) {
        $("#" + regs[i].id).removeClass("ui-btn-icon-right");
    }
};

// =============================初始化待归档(处理中)事件信息=============================
function initUnAchievedEventReg() {

    $.ajax({
        url: rootPath + "/ui/archive/initUnArchievedEventReg?device=mobile&identify=",
        dataType: 'json',
        type: 'get',
        success: function (result) {
            if (result.code == 1) {
                var regs = result.data.unArchievedEventReg;
                unArchievedEventReg("#unArchievedEventReg", regs);
            }
        }
    });
};

